import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:reorderables/reorderables.dart';

import '../../data/providers/device_provider.dart';
import '../widgets/device_card.dart';
import '../widgets/room_selector.dart';
import '../widgets/environment_info.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 100),
      vsync: this,
    );

    // 启动动画
    _animationController.repeat(reverse: true);

    // 初始化设备数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<DeviceProvider>(context, listen: false).initData();
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DeviceProvider>(
      builder: (context, deviceProvider, child) {
        final devices = deviceProvider.getDevicesByRoom();
        final isEditMode = deviceProvider.isEditMode;
        
        /// 处理重新排序的函数
        void handleReorder(int oldIndex, int newIndex) {
          if (isEditMode) {
            deviceProvider.reorderDevices(oldIndex, newIndex);
          }
          // 如果不是编辑模式，什么也不做
        }

        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.black),
              onPressed: () => Navigator.of(context).pop(),
            ),
            title: const Text(
              '自定义卡片顺序',
              style: TextStyle(color: Colors.black),
            ),
            actions: [
              TextButton(
                onPressed: deviceProvider.toggleEditMode,
                child: Text(
                  isEditMode ? '完成' : '编辑',
                  style: const TextStyle(color: Colors.black),
                ),
              ),
            ],
          ),
          body: Column(
            children: [
              // 环境信息
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: EnvironmentInfo(),
              ),
              // 房间选择器
              RoomSelector(
                rooms: deviceProvider.rooms,
                selectedRoom: deviceProvider.selectedRoom,
                onRoomSelected: deviceProvider.selectRoom,
              ),
              // 设备列表
              Expanded(
                child: ReorderableWrap(
                  spacing: 16.0,
                  runSpacing: 16.0,
                  padding: const EdgeInsets.all(16),
                  children: devices.map((device) {
                    return DeviceCard(
                      key: ValueKey(device.id),
                      device: device,
                      isEditMode: isEditMode,
                      animationController: _animationController,
                      onToggle: () => deviceProvider.toggleDeviceStatus(device.id),
                    );
                  }).toList(),
                  onReorder: handleReorder,
                  onNoReorder: (int index) {
                    // 拖动取消
                    debugPrint('拖动取消: index:$index');
                  },
                  onReorderStarted: (int index) {
                    // 开始拖动
                    debugPrint('开始拖动: index:$index');
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}